package drds.global_transaction.resource_manager.undolog.undo_executor;

import drds.common.ShouldNeverHappenException;
import drds.global_transaction.resource_manager.model.Column;
import drds.global_transaction.resource_manager.model.Image;
import drds.global_transaction.resource_manager.model.KeyType;
import drds.global_transaction.resource_manager.model.Record;
import drds.global_transaction.resource_manager.undolog.UndoLog;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class InsertUndoExecutor extends UndoExecutor
{

	public InsertUndoExecutor(UndoLog undoLog)
	{
		super(undoLog);
	}

	@Override
	protected String buildUndoSql()
	{
		Image afterImage = undoLog.getAfterImage();
		List<Record> afterImageRecords = afterImage.getRecordList();
		if (afterImageRecords == null || afterImageRecords.size() == 0)
		{
			throw new ShouldNeverHappenException("invalid undo log");
		}
		Record record = afterImageRecords.get(0);
		StringBuilder sb = new StringBuilder("delete from " + undoLog.getTableName());
		StringBuilder where = new StringBuilder(" where ");
		for (Column column : record.getColumnList())
		{
			if (column.getKeyType() == KeyType.primary_key)
			{
				where.append(column.getName() + " = ? ");
			}

		}
		return sb.append(where).toString();
	}

	@Override
	protected Image getUndoImage()
	{
		return undoLog.getAfterImage();
	}

	@Override
	protected void setValuesForUndoPreparedStatement(PreparedStatement preparedStatement, ArrayList<Column> columnList, Column primaryKeyValue) throws SQLException
	{
		preparedStatement.setObject(1, primaryKeyValue.getValue(), primaryKeyValue.getType());
	}
}
